package server;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

import shared.Packet1Chat;
import shared.Packet2Userlist;

public class ConnectionManager {
    public ArrayList<ClientConnection> connections = new ArrayList<ClientConnection>();
    public TestingServer host;

    public ConnectionManager(TestingServer host){
        this.host = host;
    }

    public void addConnection(ClientConnection user){
        if(!connections.contains(user)){
            connections.add(user);
            user.style = host.styleManager.styles[(connections.size()-1)%5];
        }
    }

    public void removeConnection(ClientConnection user){
        try {
            host.packetHandler.sendGlobalPacket(new Packet1Chat("Network: Connection lost from " + user.name + "."));
            host.serverGUI.addLine("Removing connection " + InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {}
        if(connections.contains(user))
            connections.remove(user);
        host.packetHandler.sendGlobalPacket(new Packet2Userlist(getNames()));
        host.serverGUI.updateUserList(getNames());
    }

    public ArrayList<String> getNames(){
        ArrayList<String> nameList = new ArrayList<String>();
        for(ClientConnection user : connections)
            nameList.add(user.name);
        return nameList;
    }
    
    public boolean doesNameExist(String name){
    	for(String localNames : getNames())
    		if(name.equalsIgnoreCase(localNames))
    			return true;
    	return false;
    }
}
